package main;

import geo.ResultSet;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Scanner;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;

public class Main {
	private Scanner scanner;
	private static final String baseURI = "http://where.yahooapis.com/geocode?q=";

	private Main() {
		super();
		scanner = new Scanner(System.in);
	}

	private void go() {
		String ubicacion = pideUbicacion();
		InputStream xml = pideInformacionAServicio(ubicacion);
		ResultSet resultSet = marshall(xml);
		System.out.println(resultSet);
	}

	private String pideUbicacion() {
		System.out.print("Ubicacion: ");
		return scanner.nextLine();
	}

	private InputStream pideInformacionAServicio(String ubicacion) {
		try {
			String finalURI = baseURI + URLEncoder.encode(ubicacion, "UTF-8");
			GetMethod httpMethod = new GetMethod(finalURI);
			HttpClient httpClient = new HttpClient();
			int responseCode = httpClient.executeMethod(httpMethod);
			if (responseCode == HttpStatus.SC_OK)
				return httpMethod.getResponseBodyAsStream();
			else
				return null;
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private ResultSet marshall(InputStream xml) {
		JAXBContext jaxbContext;
		try {
			jaxbContext = JAXBContext.newInstance("geo");
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			ResultSet resultSet = (ResultSet) unmarshaller.unmarshal(xml);
			return resultSet;
		} catch (JAXBException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void main(String[] args) {
		new Main().go();
	}

}
